<?php
/**
 * @title 137. 只出现一次的数字 II - 位统计
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function singleNumber($nums) {
        /**
         * @since 2021-09-02 统计每一位1的数量
         */
        $cntArray = array_fill(0, 32, 0);

        /**
         * @since 2021-09-02 统计次数
         */
        foreach ($nums as $num){
            $numBinStr = decbin($num);

            for($i=strlen($numBinStr)-1, $j=31; $i>=0 AND $j>=0; $i--, $j--){
                if($numBinStr[$i] == "1"){
                    $cntArray[$j] += 1;
                } else {}
            }
        }

        /**
         * @since 2021-09-02 取模3
         */
        foreach ($cntArray as $k=>$cnt){
            $cntArray[$k] = $cnt % 3;
        }
        // return $cntArray;

        /**
         * @return
         */
        $num = bindec(implode("", $cntArray));
        if($cntArray[0] == 1){
            $num -= pow(2, 32);
        } else {}
        return $num;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.07_8.php
 */
$datas = [
    // [2,2,3,2],
    // [0,1,0,1,0,1,99],
    // [0,1,0,1,0,1,2],
    [-2,-2,1,1,4,1,4,4,-4,-2], // -4
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->singleNumber($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
